<template>
  <view class="upload-test-page">
    <!-- 配置加载状态提示 -->
    <view v-if="configLoading" class="config-loading">
      <uni-icons type="spinner-cycle" size="16" color="#409eff"></uni-icons>
      <text class="loading-text">正在加载存储配置...</text>
    </view>

    <view v-else-if="!configLoaded" class="config-error">
      <uni-icons type="info" size="16" color="#f56c6c"></uni-icons>
      <text class="error-text">存储配置加载失败，请刷新页面重试</text>
      <view class="retry-btn" @click="preloadStorageConfigs">重试</view>
    </view>

    <!-- 标签页切换 -->
    <view class="tab-bar">
      <view
          v-for="tab in tabs"
          :key="tab.key"
          class="tab-item"
          :class="{ active: activeTab === tab.key }"
          @click="switchTab(tab.key)"
      >
        <text class="tab-text">{{ tab.label }}</text>
        <view class="tab-badge" :class="tab.type">{{ tab.badge }}</view>
      </view>
    </view>

    <!-- 文件上传测试 -->
    <view v-if="activeTab === 'file'" class="tab-content">
      <view class="test-card">
        <view class="card-header">
          <text class="card-title">FileUpload 组件测试</text>
          <view class="card-badge primary">通用文件上传</view>
        </view>

        <view class="demo-section">
          <text class="section-title">组件特点：</text>
          <view class="feature-list">
            <view class="feature-item">📁 支持点击选择文件</view>
            <view class="feature-item">🔄 小于20MB自动普通上传，大于20MB自动分片上传</view>
            <view class="feature-item">☁️ 支持前端直传（MinIO/阿里云/腾讯云/AWS）</view>
            <view class="feature-item">📊 实时上传进度显示</view>
            <view class="feature-item">🔢 支持多文件上传和数量限制</view>
            <view class="feature-item">🛡️ 文件类型和大小验证（基于存储配置）</view>
            <view class="feature-item">⚙️ 文件大小限制自动从存储配置获取</view>
          </view>

          <!-- 组件配置 -->
          <view class="config-section">
            <text class="config-title">配置选项</text>
            <view class="config-form">
              <view class="form-item">
                <text class="form-label">最大文件数：</text>
                <view class="number-input">
                  <view class="btn-decrease" @click="decreaseFileLimit">-</view>
                  <text class="number-value">{{ fileConfig.limit }}</text>
                  <view class="btn-increase" @click="increaseFileLimit">+</view>
                </view>
              </view>
            </view>
          </view>

          <!-- FileUpload 组件 -->
          <FileUpload
              :limit="fileConfig.limit"
              default-dir=""
              @upload-success="handleFileUploadSuccess"
              @upload-error="handleFileUploadError"
              @upload-progress="handleFileUploadProgress"
          />
        </view>
      </view>
    </view>

    <!-- 图片上传测试 -->
    <view v-if="activeTab === 'image'" class="tab-content">
      <view class="test-card">
        <view class="card-header">
          <text class="card-title">ImageUpload 组件测试</text>
          <view class="card-badge success">专为图片优化</view>
        </view>

        <view class="demo-section">
          <text class="section-title">组件特点：</text>
          <view class="feature-list">
            <view class="feature-item">🖼️ 专门针对图片格式优化</view>
            <view class="feature-item">🔍 内置图片预览功能</view>
            <view class="feature-item">🎯 支持网格和列表两种布局</view>
            <view class="feature-item">📸 自动生成缩略图</view>
            <view class="feature-item">⚡ 自动上传模式</view>
            <view class="feature-item">🗜️ 智能图片压缩（质量/大小压缩）</view>
            <view class="feature-item">🔧 自动转换为.jpg格式</view>
            <view class="feature-item">📱 跨平台兼容（H5/小程序/App）</view>
          </view>

          <!-- 组件配置 -->
          <view class="config-section">
            <text class="config-title">配置选项</text>
            <view class="config-form">
              <view class="form-item">
                <text class="form-label">最大图片数：</text>
                <view class="number-input">
                  <view class="btn-decrease" @click="decreaseImageCount">-</view>
                  <text class="number-value">{{ imageConfig.maxCount }}</text>
                  <view class="btn-increase" @click="increaseImageCount">+</view>
                </view>
              </view>
              <view class="form-item">
                <text class="form-label">布局模式：</text>
                <view class="radio-group">
                  <view
                      class="radio-item"
                      :class="{ active: imageConfig.layout === 'grid' }"
                      @click="setImageLayout('grid')"
                  >
                    <text class="radio-text">网格</text>
                  </view>
                  <view
                      class="radio-item"
                      :class="{ active: imageConfig.layout === 'list' }"
                      @click="setImageLayout('list')"
                  >
                    <text class="radio-text">列表</text>
                  </view>
                </view>
              </view>
              <view class="form-item">
                <text class="form-label">启用压缩：</text>
                <view class="switch-container">
                  <switch 
                    :checked="imageConfig.enableCompress" 
                    @change="onCompressSwitchChange"
                    color="#409eff"
                  />
                </view>
              </view>
              <template v-if="imageConfig.enableCompress">
                <view class="form-item">
                  <text class="form-label">压缩模式：</text>
                  <view class="radio-group">
                    <view
                        class="radio-item"
                        :class="{ active: imageConfig.compressMode === 'quality' }"
                        @click="setCompressMode('quality')"
                    >
                      <text class="radio-text">质量压缩</text>
                    </view>
                    <view
                        class="radio-item"
                        :class="{ active: imageConfig.compressMode === 'size' }"
                        @click="setCompressMode('size')"
                    >
                      <text class="radio-text">大小压缩</text>
                    </view>
                  </view>
                </view>
                <view v-if="imageConfig.compressMode === 'quality'" class="form-item">
                  <text class="form-label">压缩质量：{{ (imageConfig.compressQuality * 100).toFixed(0) }}%</text>
                  <view class="slider-container">
                    <slider 
                      :value="imageConfig.compressQuality * 100"
                      min="10" 
                      max="100" 
                      step="5"
                      backgroundColor="#e4e7ed"
                      activeColor="#409eff"
                      @change="onQualitySliderChange"
                    />
                  </view>
                </view>
                <view v-if="imageConfig.compressMode === 'size'" class="form-item">
                  <text class="form-label">目标大小：{{ imageConfig.maxFileSizeKb }}KB</text>
                  <view class="number-input">
                    <view class="btn-decrease" @click="decreaseTargetSize">-</view>
                    <text class="number-value">{{ imageConfig.maxFileSizeKb }}</text>
                    <view class="btn-increase" @click="increaseTargetSize">+</view>
                  </view>
                </view>
              </template>
            </view>
          </view>

          <!-- 压缩功能说明 -->
          <view v-if="imageConfig.enableCompress" class="alert-box info compress-info">
            <uni-icons type="info" size="16" color="#409eff"></uni-icons>
            <view class="alert-content">
              <text class="alert-title">图片压缩说明</text>
              <text class="alert-text">✨ 质量压缩：根据质量参数，自动设置尺寸（质量越低，尺寸越小）</text>
              <text class="alert-text">📏 大小压缩：智能迭代调整尺寸和质量，精确压缩至目标大小</text>
              <text class="alert-text">🔧 质量 ≤20%: 宽600px | 40%: 宽1000px | 60%: 宽1500px | 80%: 宽2000px</text>
              <text class="alert-text">📱 使用 watasi-compress 插件，支持H5、小程序、App全平台</text>
            </view>
          </view>

          <!-- ImageUpload 组件 -->
          <ImageUpload
              :max-count="imageConfig.maxCount"
              :layout="imageConfig.layout"
              :enable-compress="imageConfig.enableCompress"
              :compress-mode="imageConfig.compressMode"
              :compress-quality="imageConfig.compressQuality"
              :max-file-size-kb="imageConfig.maxFileSizeKb"
              :min-compress-size="imageConfig.minCompressSize"
              default-dir=""
              @upload-success="handleImageUploadSuccess"
              @upload-error="handleImageUploadError"
              @preview="handleImagePreview"
              @remove="handleImageRemove"
              @compress-start="handleCompressStart"
              @compress-end="handleCompressEnd"
          />
        </view>
      </view>
    </view>

    <!-- 分片上传演示 -->
    <view v-if="activeTab === 'chunk'" class="tab-content">
      <view class="test-card">
        <view class="card-header">
          <text class="card-title">分片上传演示</text>
          <view class="card-badge warning">大文件上传</view>
        </view>

        <view class="demo-section">
          <view class="alert-box info">
            <uni-icons type="info" size="16" color="#409eff"></uni-icons>
            <view class="alert-content">
              <text class="alert-title">分片上传说明</text>
              <text class="alert-text">分片上传适用于大文件（>20MB），将文件分割成小块并发上传，提高上传成功率。</text>
              <text class="alert-text">FileUpload 组件会自动判断文件大小，超过20MB时自动启用分片上传。</text>
              <text class="alert-text">✨ 新增重试机制：每个分片失败后会自动重试3次，采用指数退避策略。</text>
              <text class="alert-text">🛡️ 智能错误处理：错误率超过50%时会自动停止上传，避免无效重试。</text>
            </view>
          </view>

          <!-- 大文件上传演示 -->
          <view class="chunk-demo">
            <text class="section-title">大文件上传演示：</text>
            <FileUpload
                :limit="1"
                default-dir=""
                @upload-success="handleChunkUploadSuccess"
                @upload-error="handleChunkUploadError"
                @upload-progress="handleChunkUploadProgress"
            />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import FileUpload from '@/components/FileUpload/index.vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import {useFileConfigStore} from '@/store/modules/fileConfig'

export default {
  name: 'UploadTest',
  components: {
    FileUpload,
    ImageUpload
  },
  data() {
    return {
      // 当前选中的标签页
      activeTab: 'file',

      // 标签页配置
      tabs: [
        {key: 'file', label: '文件上传', badge: '通用', type: 'primary'},
        {key: 'image', label: '图片上传', badge: '专业', type: 'success'},
        {key: 'chunk', label: '分片上传', badge: '大文件', type: 'warning'}
      ],

      // 文件上传配置
      fileConfig: {
        limit: 5
      },

      // 图片上传配置
      imageConfig: {
        maxCount: 5,
        layout: 'grid',
        enableCompress: true,
        compressMode: 'size', // 'quality' | 'size'
        compressQuality: 0.8,
        maxFileSizeKb: 50,
        minCompressSize: 10
      },

      // 图片预览相关（用于演示ImagePreview组件）
      previewVisible: false,
      currentPreviewIndex: 0,

      // 存储配置状态
      configLoading: false,
      configLoaded: false
    }
  },
  async onLoad() {
    uni.setNavigationBarTitle({
      title: '文件上传测试'
    })

    // 预加载存储配置
    await this.preloadStorageConfigs()
  },
  methods: {
    // 标签页切换
    switchTab(tabKey) {
      this.activeTab = tabKey
    },

    // 文件配置相关方法
    decreaseFileLimit() {
      if (this.fileConfig.limit > 1) {
        this.fileConfig.limit--
      }
    },
    increaseFileLimit() {
      if (this.fileConfig.limit < 10) {
        this.fileConfig.limit++
      }
    },

    // 图片配置相关方法
    decreaseImageCount() {
      if (this.imageConfig.maxCount > 1) {
        this.imageConfig.maxCount--
      }
    },
    increaseImageCount() {
      if (this.imageConfig.maxCount < 10) {
        this.imageConfig.maxCount++
      }
    },
    setImageLayout(layout) {
      this.imageConfig.layout = layout
    },

    // 压缩配置相关方法
    onCompressSwitchChange(event) {
      this.imageConfig.enableCompress = event.detail.value
    },
    setCompressMode(mode) {
      this.imageConfig.compressMode = mode
    },
    onQualitySliderChange(event) {
      this.imageConfig.compressQuality = event.detail.value / 100
    },
    decreaseTargetSize() {
      if (this.imageConfig.maxFileSizeKb > 10) {
        // 根据当前值调整步进
        const step = this.imageConfig.maxFileSizeKb > 100 ? 50 : 10
        this.imageConfig.maxFileSizeKb = Math.max(10, this.imageConfig.maxFileSizeKb - step)
      }
    },
    increaseTargetSize() {
      if (this.imageConfig.maxFileSizeKb < 2048) {
        // 根据当前值调整步进
        const step = this.imageConfig.maxFileSizeKb >= 100 ? 50 : 10
        this.imageConfig.maxFileSizeKb += step
      }
    },

    // 文件上传事件处理
    handleFileUploadSuccess(event) {
      uni.showToast({
        title: `文件 ${event.file.name} 上传成功`,
        icon: 'success'
      })
    },

    handleFileUploadError(event) {
      uni.showToast({
        title: `文件 ${event.file.name} 上传失败`,
        icon: 'error'
      })
    },

    handleFileUploadProgress(event) {
      // 可以在这里处理进度
    },

    // 图片上传事件处理
    handleImageUploadSuccess(event) {
      uni.showToast({
        title: `图片 ${event.file.name} 上传成功`,
        icon: 'success'
      })
    },

    handleImageUploadError(event) {
      uni.showToast({
        title: `图片 ${event.file.name} 上传失败`,
        icon: 'error'
      })
    },

    handleImagePreview(event) {
      // 图片预览处理
    },

    handleImageRemove(event) {
      // 图片移除处理
    },

    // 压缩事件处理
    handleCompressStart(event) {
      console.log('开始压缩图片:', event.file)
      // 可以在这里显示压缩开始的提示
    },

    handleCompressEnd(event) {
      console.log('图片压缩完成:', {
        原始文件: event.originalFile.name,
        压缩后文件: event.compressedFile.name,
        原始大小: (event.originalSize / 1024).toFixed(1) + 'KB',
        压缩后大小: (event.newSize / 1024).toFixed(1) + 'KB',
        压缩率: event.compressRatio + '%'
      })
      
      // 显示压缩结果提示
      uni.showToast({
        title: `图片压缩完成，压缩率: ${event.compressRatio}%`,
        icon: 'success',
        duration: 2000
      })
    },

    // 分片上传事件处理
    handleChunkUploadSuccess(event) {
      uni.showToast({
        title: `大文件 ${event.file.name} 分片上传成功`,
        icon: 'success'
      })
    },

    handleChunkUploadError(event) {
      uni.showToast({
        title: `大文件 ${event.file.name} 分片上传失败`,
        icon: 'error'
      })
    },

    handleChunkUploadProgress(event) {
      // 分片上传进度处理
    },


    // 预加载存储配置
    async preloadStorageConfigs() {
      if (this.configLoading || this.configLoaded) return

      this.configLoading = true

      try {
        const fileConfigStore = useFileConfigStore()

        // 预加载配置，确保组件可以使用
        await fileConfigStore.preloadConfigs()

        this.configLoaded = true

        uni.showToast({
          title: '配置加载完成',
          icon: 'success',
          duration: 1500
        })

      } catch (error) {
        uni.showToast({
          title: '配置加载失败，请检查网络',
          icon: 'error',
          duration: 3000
        })
      } finally {
        this.configLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-test-page {
  min-height: 100vh;
  background: #f5f7fa;
}

// 配置加载状态
.config-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  padding: 32rpx;
  background: #f0f9ff;
  border-bottom: 1px solid #b3d8ff;

  .loading-text {
    font-size: 26rpx;
    color: #409eff;
  }
}

.config-error {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  background: #fef0f0;
  border-bottom: 1px solid #fbc4c4;

  .error-text {
    font-size: 26rpx;
    color: #f56c6c;
    flex: 1;
    margin: 0 16rpx;
  }

  .retry-btn {
    padding: 8rpx 16rpx;
    background: #f56c6c;
    color: #fff;
    border-radius: 6rpx;
    font-size: 24rpx;

    &:active {
      background: #f04747;
    }
  }
}

// 标签页样式
.tab-bar {
  display: flex;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  position: sticky;
  top: 0;
  z-index: 100;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx 16rpx;
  position: relative;

  &.active {
    .tab-text {
      color: #409eff;
      font-weight: 600;
    }

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background: #409eff;
      border-radius: 2rpx;
    }
  }
}

.tab-text {
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 8rpx;
}

.tab-badge {
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  color: #fff;

  &.primary {
    background: #409eff;
  }

  &.success {
    background: #67c23a;
  }

  &.warning {
    background: #e6a23c;
  }
}

// 内容区域
.tab-content {
  padding: 32rpx;
}

.test-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
  padding-bottom: 24rpx;
  border-bottom: 1px solid #f0f0f0;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #303133;
}

.card-badge {
  font-size: 22rpx;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  color: #fff;

  &.primary {
    background: #409eff;
  }

  &.success {
    background: #67c23a;
  }

  &.warning {
    background: #e6a23c;
  }
}

.demo-section {
  .section-title {
    display: block;
    font-size: 28rpx;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16rpx;
  }
}

.feature-list {
  margin-bottom: 32rpx;
}

.feature-item {
  padding: 12rpx 0;
  font-size: 26rpx;
  color: #606266;
  line-height: 1.5;
}

// 配置区域
.config-section {
  background: #f8f9fa;
  padding: 32rpx;
  border-radius: 12rpx;
  margin-bottom: 32rpx;
}

.config-title {
  display: block;
  font-size: 26rpx;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24rpx;
}

.config-form {
  .form-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .form-label {
    font-size: 26rpx;
    color: #606266;
  }
}

.number-input {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 8rpx;
  overflow: hidden;

  .btn-decrease,
  .btn-increase {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
    color: #606266;
    font-size: 32rpx;
    border: none;

    &:active {
      background: #e6e8eb;
    }
  }

  .number-value {
    min-width: 80rpx;
    text-align: center;
    font-size: 26rpx;
    color: #303133;
    background: #fff;
    height: 60rpx;
    line-height: 60rpx;
  }
}

.radio-group {
  display: flex;
  gap: 16rpx;
}

.radio-item {
  padding: 12rpx 24rpx;
  border: 1px solid #dcdfe6;
  border-radius: 8rpx;
  background: #fff;

  &.active {
    border-color: #409eff;
    background: #f0f9ff;

    .radio-text {
      color: #409eff;
    }
  }
}

.radio-text {
  font-size: 24rpx;
  color: #606266;
}

// 开关样式
.switch-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

// 滑块样式
.slider-container {
  flex: 1;
  margin-left: 24rpx;
  max-width: 300rpx;
}


// 提示框
.alert-box {
  padding: 24rpx;
  border-radius: 8rpx;
  margin-bottom: 32rpx;
  display: flex;
  align-items: flex-start;
  gap: 16rpx;

  &.info {
    background: #f0f9ff;
    border: 1px solid #b3d8ff;
  }

  .alert-content {
    flex: 1;

    .alert-title {
      display: block;
      font-size: 26rpx;
      font-weight: 600;
      color: #303133;
      margin-bottom: 8rpx;
    }

    .alert-text {
      display: block;
      font-size: 24rpx;
      color: #606266;
      line-height: 1.5;
      margin-bottom: 8rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  &.compress-info {
    margin-top: 24rpx;
    margin-bottom: 24rpx;
  }
}

// 分片上传演示
.chunk-demo {
  margin-top: 32rpx;
  padding: 32rpx;
  background: #fff7e6;
  border-radius: 12rpx;
  border: 1px solid #ffd591;

  .section-title {
    color: #d46b08;
    margin-bottom: 24rpx;
  }
}
</style>
